<template>
  <div>
    <van-nav-bar safe-area-inset-top placeholder :title="$t('AddSiteInformation')" left-arrow fixed @click-left="onClickLeft">
      <template #right>
        <span class="white" @click="getPosition">{{$t('reLocate')}}</span>
      </template>
    </van-nav-bar>

    <van-form name="addSite" @submit="addSite">
      <div class="registered_box">
        <div class="registered_li">
          <div class="registered_li_tit required">{{$t('SiteName')}}</div>
          <div class="registered_li_ipt">
            <van-field clearable name="siteName" v-model="siteName" type="text" />
          </div>
        </div>
        <div class="registered_li">
          <div class="registered_li_tit required">{{$t('PanelSize')}}(kW)</div>
          <div class="registered_li_ipt">
            <van-field clearable v-model="capacity" type="number" />
          </div>
        </div>
        <div class="registered_li">
          <div class="registered_li_tit required">{{$t('TimeZone')}}</div>
          <div class="registered_li_ipt" @click="showTimeZone">
            <van-field readonly clickable name="timeZone" v-model="timeZone" type="text" />
          </div>
          <timeZoneList ref="timezone" @getTimeZone="getTimeZone"></timeZoneList>
        </div>
        <div class="registered_li">
          <div class="registered_li_tit required">{{$t('Nation')}}</div>
          <div class="registered_li_ipt" @click="showNation">
            <van-field readonly clickable name="nation" v-model="nation" type="text" />
          </div>
          <nationList ref="nation" @getNation="getNation"></nationList>
        </div>
        <div v-if="!notChina">
          <div class="registered_li">
            <div class="registered_li_tit required">{{$t('Area')}}</div>
            <div class="registered_li_ipt">
              <van-field type="text" readonly clickable :value="address" @click="showPicker = true" />
              <van-popup v-model="showPicker" round position="bottom">
                <van-area 
                  :area-list="areaList"
                  @cancel="showPicker = false"
                  @confirm="onConfirm" 
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
            </div>
          </div>
          <div class="registered_li">
            <div class="registered_li_tit required">{{$t('Address')}}</div>
            <div class="registered_li_ipt">
              <van-field type="text" readonly clickable :value="address_detail" @click="showAdrDetail = true" />
              <van-popup v-model="showAdrDetail" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="adrDetailArr"
                  @cancel="showAdrDetail = false"
                  @confirm="adrDetailConfirm"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
            </div>
          </div>
        </div>
        <div class="registered_li" v-if="notChina">
          <div class="registered_li_tit required">{{$t('Postcode')}}</div>
          <div class="registered_li_ipt">
            <van-field clearable v-model="postcode" type="text" />
          </div>
        </div>
      </div>
      <div class="siteInfo">
        <div class="siteInfo_t">
          <van-checkbox v-model="useSeasonal" checked-color="#F39800">{{$t('UseSeasonal')}}</van-checkbox>
        </div>
        <div v-if="useSeasonal">
          <div class="addSiteType_box">
            <div class="addSiteType_box_l">{{$t('Type')}}</div>
            <div class="addSiteType_box_r" @click="showPicker2=true">{{byTime}}</div>
            <van-popup v-model="showPicker2" round position="bottom">
              <van-picker
                show-toolbar
                :columns="byTimeArr"
                @cancel="showPicker2 = false"
                @confirm="onConfirm2"
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')"
              />
            </van-popup>
          </div>
          <div v-if="byTime== byTimeArr[1]">
            <div class="addSiteType_box">
              <div class="addSiteType_box_l">{{$t('StartTime')}}</div>
              <div class="addSiteType_box_r">
                <div class="inner" @click="showPicker3=true">{{byDateStartMVal}}</div>
                <div class="inner" @click="showPicker4=true">{{byDateStartDVal}}</div>
              </div>
              <van-popup v-model="showPicker3" round position="bottom">
                <van-datetime-picker
                  v-model="byDateStartM"
                  type="month-day"
                  @cancel="showPicker3 = false"
                  @confirm="onConfirm3"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
              <van-popup v-model="showPicker4" round position="bottom">
                <van-datetime-picker
                  v-model="byDateStartDVal"
                  type="time"
                  @cancel="showPicker4 = false"
                  @confirm="onConfirm4"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
            </div>
            <div class="addSiteType_box">
              <div class="addSiteType_box_l">{{$t('EndTime')}}</div>
              <div class="addSiteType_box_r">
                <div class="inner" @click="showPicker5=true">{{byDateEndMVal}}</div>
                <div class="inner" @click="showPicker6=true">{{byDateEndDVal}}</div>
              </div>
              <van-popup v-model="showPicker5" round position="bottom">
                <van-datetime-picker
                  v-model="byDateEndM"
                  type="month-day"
                  @cancel="showPicker5 = false"
                  @confirm="onConfirm5"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
              <van-popup v-model="showPicker6" round position="bottom">
                <van-datetime-picker
                  v-model="byDateEndDVal"
                  type="time"
                  @cancel="showPicker6 = false"
                  @confirm="onConfirm6"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
            </div>
          </div>
          <div v-if="byTime==byTimeArr[0]">
            <div class="addSiteType_box">
              <div class="addSiteType_box_l">{{$t('StartTime')}}</div>
              <div class="addSiteType_box_r">
                <div class="inner" @click="showPicker7=true">{{monthVal}}</div>
                <div class="inner" @click="showPicker8=true">{{orderVal}}</div>
              </div>
              <van-popup v-model="showPicker7" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="monthArr"
                  @cancel="showPicker7 = false"
                  @confirm="onConfirm7"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
              <van-popup v-model="showPicker8" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="orderArr"
                  @cancel="showPicker8 = false"
                  @confirm="onConfirm8"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
            </div>
            <div class="addSiteType_box">
              <div class="inner" @click="showPicker9=true">{{cycleValue}}</div>
              <div class="inner" @click="showPicker10=true">{{weekVal}}</div>
              <div class="inner" @click="showPicker11=true">{{byDateStartD2Val}}</div>
              <van-popup v-model="showPicker9" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="cycleArr"
                  @cancel="showPicker9 = false"
                  @confirm="onConfirm9"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
              <van-popup v-model="showPicker10" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="weekArr"
                  @cancel="showPicker10 = false"
                  @confirm="onConfirm10"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
              <van-popup v-model="showPicker11" round position="bottom">
                <van-datetime-picker
                  v-model="byDateStartD2Val"
                  type="time"
                  @cancel="showPicker11 = false"
                  @confirm="onConfirm11"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
            </div>
            <div class="addSiteType_box">
              <div class="addSiteType_box_l">{{$t('EndTime')}}</div>
              <div class="addSiteType_box_r">
                <div class="inner" @click="showPicker12=true">{{monthVal2}}</div>
                <div class="inner" @click="showPicker13=true">{{orderVal2}}</div>
              </div>
              <van-popup v-model="showPicker12" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="monthArr"
                  @cancel="showPicker12 = false"
                  @confirm="onConfirm12"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
              <van-popup v-model="showPicker13" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="orderArr"
                  @cancel="showPicker13 = false"
                  @confirm="onConfirm13"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
            </div>
            <div class="addSiteType_box">
              <div class="inner" @click="showPicker14=true">{{cycleValue2}}</div>
              <div class="inner" @click="showPicker15=true">{{weekVal2}}</div>
              <div class="inner" @click="showPicker16=true">{{byDateEndD2Val}}</div>
              <van-popup v-model="showPicker14" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="cycleArr"
                  @cancel="showPicker14 = false"
                  @confirm="onConfirm14"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
              <van-popup v-model="showPicker15" round position="bottom">
                <van-picker
                  show-toolbar
                  :columns="weekArr"
                  @cancel="showPicker15 = false"
                  @confirm="onConfirm15"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
              <van-popup v-model="showPicker16" round position="bottom">
                <van-datetime-picker
                  v-model="byDateEndD2Val"
                  type="time"
                  @cancel="showPicker16 = false"
                  @confirm="onConfirm16"
                  :confirm-button-text="$t('OK')"
                  :cancel-button-text="$t('Cancel')"
                />
              </van-popup>
            </div>
          </div>
        </div>
      </div>
      <div class="addSite_Agreement">
        <van-checkbox class="authorCheck" v-model="authorizeFlag" checked-color="#F39800"></van-checkbox>{{$t('addSiteAgree')}}</div>
      <div class="btnBox">
        <van-button color="linear-gradient(#F9C25F, #F5861A)" :disabled="siteName==''||capacity==''||timeZone==''||nation==''||(postcode==''&&notChina)||(address==''&&!notChina)" round block native-type="submit">{{$t('AddSiteInformation')}}</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant';
import moment from 'moment'
import AreaList from '../api/area'
import timeZoneList from '../components/IndexBar/TimeZoneList'
import nationList from '../components/IndexBar/NationList'

export default {
  components:{
    timeZoneList,
    nationList
  },
  data(){
    return {
      siteName:'My Site',
      capacity:'',
      timeZone:'',
      nation:'',
      notChina:true,
      showPicker: false,
      address:'北京市-北京市-东城区',
      areaList:AreaList,
      showAdrDetail:false,
      address_detail:'东华门街道办事处',
      adrDetailArr:[],
      postcode:'',
      useSeasonal:false,
      byTime:this.$t('ByWeek'),
      showPicker2: false,
      byTimeArr:[this.$t('ByWeek'),this.$t('ByDate')],
      showPicker3:false,
      byDateStartMVal:moment(new Date()).format('MM/DD'),
      byDateStartM:new Date(),
      showPicker4:false,
      byDateStartDVal:moment(new Date()).format('HH:mm'),
      showPicker5:false,
      byDateEndMVal:moment(new Date()).format('MM/DD'),
      byDateEndM:new Date(),
      showPicker6:false,
      byDateEndDVal:moment(new Date()).format('HH:mm'),
      showPicker7:false,
      monthVal:this.$t('January'),
      monthArr:[this.$t('January'),this.$t('February'),this.$t('March'),this.$t('April'),this.$t('May'),this.$t('June'),this.$t('July'),this.$t('August'),this.$t('September'),this.$t('October'),this.$t('November'),this.$t('December')],
      showPicker8:false,
      orderVal:this.$t('Positive'),
      orderArr:[this.$t('Positive'),this.$t('Reciprocal')],
      showPicker9:false,
      cycleValue:this.$t('Week1'),
      cycleArr:[this.$t('Week1'),this.$t('Week2'),this.$t('Week3'),this.$t('Week4'),this.$t('Week5')],
      showPicker10:false,
      weekVal:this.$t('Monday'),
      weekArr:[this.$t('Monday'),this.$t('Tuesday'),this.$t('Wednesday'),this.$t('Thursday'),this.$t('Friday'),this.$t('Saturday'),this.$t('Sunday')],
      showPicker11:false,
      byDateStartD2Val:moment(new Date()).format('HH:mm'),
      showPicker12:false,
      monthVal2:this.$t('January'),
      showPicker13:false,
      orderVal2:this.$t('Positive'),
      showPicker14:false,
      cycleValue2:this.$t('Week1'),
      showPicker15:false,
      weekVal2:this.$t('Monday'),
      showPicker16:false,
      byDateEndD2Val:moment(new Date()).format('HH:mm'),
      authorizeFlag:true,
      isGeolocation:false,//是否开启定位功能
      latitude:'',//纬度
      longitude:''//经度
    }
  },
  methods: {
    onClickLeft(){
      this.$router.push({path:'/scan'});
    },
    showTimeZone(){
      this.$refs.timezone.openTimeZone(true);
    },
    getTimeZone(data){
      this.timeZone=data;
    },
    showNation(){
      this.$refs.nation.openNation(true);
    },
    getNation(data){
      this.nation=data;
      if(data!="中国"){
        this.notChina=true;
      }else{
        this.notChina=false;
      }
    },
    onConfirm(value) {
      this.address = `${value[0].name}-${value[1].name}-${value[2].name}`;
      this.adrDetailArr=this.addressDetail.getAddress(`${value[1].name}-${value[2].name}`);
      this.address_detail=this.adrDetailArr[0];
      this.showPicker = false;
    },
    adrDetailConfirm(data){
      this.showAdrDetail=false;
      this.address_detail=data;
    },
    onConfirm2(value) {
      this.byTime = value;
      this.showPicker2 = false;
    },
    onConfirm3(value) {
      this.byDateStartMVal = moment(value).format('MM/DD');
      this.showPicker3 = false;
    },
    onConfirm4(value) {
      this.byDateStartDVal = value;
      this.showPicker4 = false;
    },
    onConfirm5(value){
      this.byDateEndMVal = moment(value).format('MM/DD');
      this.showPicker5 = false;
    },
    onConfirm6(value){
      this.byDateEndDVal = value;
      this.showPicker6 = false;
    },
    onConfirm7(value){
      this.monthVal = value;
      this.showPicker7 = false;
    },
    onConfirm8(value){
      this.orderVal = value;
      this.showPicker8 = false;
    },
    onConfirm9(value){
      this.cycleValue = value;
      this.showPicker9 = false;
    },
    onConfirm10(value){
      this.weekVal = value;
      this.showPicker10 = false;
    },
    onConfirm11(value){
      this.byDateStartD2Val = value;
      this.showPicker11 = false;
    },
    onConfirm12(value){
      this.monthVal2 = value;
      this.showPicker12 = false;
    },
    onConfirm13(value){
      this.orderVal2 = value;
      this.showPicker13 = false;
    },
    onConfirm14(value){
      this.cycleValue2 = value;
      this.showPicker14 = false;
    },
    onConfirm15(value){
      this.weekVal2 = value;
      this.showPicker15 = false;
    },
    onConfirm16(value){
      this.byDateEndD2Val = value;
      this.showPicker16 = false;
    },
    //自动获取时区
    async autoGetTimeZone() {
      let code=Intl.DateTimeFormat().resolvedOptions().timeZone;
      let res = await this.API.selectTimeZone(1,{'lang':'zh_CN','timeZoneId':code});
      this.timeZone=res[0].timeZoneValue;
    },
    //自动获取国家
    autoLocation(){
      navigator.globalization.getLocaleName((data)=>{
        let codeArr=data.value.split('-');
        this.codeForNation(codeArr[1]);
      });
    },
    //根据code获取国家
    async codeForNation(code){
      let res = await this.API.selectCountry(1,{});
      res.forEach(element => {
        if(element.enShort==code){
          this.nation=element.enName;
          if(this.nation!="中国"){
            this.notChina=true;
          }else{
            this.notChina=false;
          }
        }
      });
    },
    //定位
    getPosition(){
      this.comm.loadingShow();
      navigator.geolocation.getCurrentPosition((position)=>{
        this.comm.toastHide();
        this.isGeolocation=true;
        //纬度
        this.latitude=position.coords.latitude;
        this.longitude=position.coords.longitude;
        this.getDF(this.latitude,this.longitude);
      }, (onError)=>{
        this.comm.toastHide();
        this.isGeolocation=false;
        this.comm.tipsShow('OpenGeolocation');
      });
    },
    //经纬度转换成地址
    async getDF(latitude,longitude){
      let res=await this.API.getAddress({
        'location':`${latitude},${longitude}`,
        'output':'json',
        'ak':'pQ960wtzzkV2whRYYI66VXGoor1TwAxU'
      });
      this.address=`${res.result.addressComponent.province}-${res.result.addressComponent.city}-${res.result.addressComponent.district}`;
      this.adrDetailArr=this.addressDetail.getAddress(`${res.result.addressComponent.city}-${res.result.addressComponent.district}`);
      this.address_detail=res.result.addressComponent.street;
    },
    async addFunc(params){
      this.comm.loadingShow();
      let res = await this.API.addSite(localStorage.getItem("domain"),params);
      if(res.success){
        this.comm.popAndJump('AddSiteSuccess','/main/sitedetail');
      }else{
        Toast.fail(this.$t('AddFaild'));
      }
    },
    async addSite(){
      let summerStartTime = '';
      let summerEndTime = '';
      if(this.useSeasonal){
        if(this.byTime== this.byTimeArr[1]){
          summerStartTime = `${(this.byDateStartMVal).split('/').join('-')} ${this.byDateStartDVal}`;
          summerEndTime = `${(this.byDateEndMVal).split('/').join('-')} ${this.byDateEndDVal}`;
        }else{
          summerStartTime = `${this.monthArr.indexOf(this.monthVal)+1};${this.orderVal == this.$t('Positive')?"+":"-"}${this.cycleArr.indexOf(this.cycleValue)+1};${this.weekArr.indexOf(this.weekVal)+1};${this.byDateStartD2Val}`;
          summerEndTime = `${this.monthArr.indexOf(this.monthVal2)+1};${this.orderVal2 == this.$t('Positive')?"+":"-"}${this.cycleArr.indexOf(this.cycleValue2)+1};${this.weekArr.indexOf(this.weekVal2)+1};${this.byDateStartDVal}`;
        }
      }
      if(this.notChina){
        if(this.isGeolocation){ 
          let params={
            'userId':localStorage.getItem('userId'),
            'siteName':encodeURI(this.siteName),
            'nation':encodeURI(this.nation),
            'timeZone':this.timeZone,
            'capacity':this.capacity,
            'postcode':this.postcode,
            'province':'',
            'city':'',
            'county':'',
            'town':'',
            'longitude':this.longitude,
            'latitude':this.latitude,
            'authorizeFlag':this.authorizeFlag==true?1:0,
            'summerStartTime':summerStartTime,
            'summerEndTime':summerEndTime,
            'wifiSn':localStorage.getItem('wifiSN')
          }
          this.addFunc(params);
        }else{
          let data = await this.API.getAddr(localStorage.getItem("domain"),{'zipCode':`${this.nation},${this.postcode}`});
          if(data.success){
            let params={
              'userId':localStorage.getItem('userId'),
              'siteName':encodeURI(this.siteName),
              'nation':encodeURI(this.nation),
              'timeZone':this.timeZone,
              'capacity':this.capacity,
              'postcode':this.postcode,
              'province':'',
              'city':'',
              'county':'',
              'town':'',
              'longitude':data.result.lng,
              'latitude':data.result.lat,
              'authorizeFlag':this.authorizeFlag==true?1:0,
              'summerStartTime':summerStartTime,
              'summerEndTime':summerEndTime,
              'wifiSn':localStorage.getItem('wifiSN')
            }
            this.addFunc(params);
          }else{
            this.comm.tipsShow('UnableGetLocation');
          }
        }
      }else{
        let params={
          'userId':localStorage.getItem('userId'),
          'siteName':encodeURI(this.siteName),
          'nation':encodeURI(this.nation),
          'timeZone':this.timeZone,
          'capacity':this.capacity,
          'postcode':'',
          'province':encodeURI(this.address.split('-')[0] || ''),
          'city':encodeURI(this.address.split('-')[1] || ''),
          'county':encodeURI(this.address.split('-')[2] || ''),
          'town':encodeURI(this.address_detail),
          'longitude':this.longitude,
          'latitude':this.latitude,
          'authorizeFlag':this.authorizeFlag==true?1:0,
          'summerStartTime':summerStartTime,
          'summerEndTime':summerEndTime,
          'wifiSn':localStorage.getItem('wifiSN')
        }
        this.addFunc(params);
      }
    }
  },
  mounted() {
    this.getPosition();
    this.autoGetTimeZone();
    this.adrDetailArr=this.addressDetail.getAddress('北京市-东城区');
    this.autoLocation();
  },
}
</script>

<style scoped lang="less">
.registered_box{
  width: 100%;
  background: #ffffff;
}
.registered_li{
  width: 100%;
  border-bottom: 1px solid #efefef;
}
.registered_li_tit{
  padding: 12px 0 0 15px;
  width: 100%;
  color: #929292;
  text-align: left;
  box-sizing: border-box;
}
.siteInfo{
  width: 100%;
  background: #ffffff;
  border-bottom: 1px solid #efefef;
}
.siteInfo_t{
  width:100%;
  height: 35px;
  padding: 8px;
  box-sizing: border-box;
}
.addSiteType_box{
  width: 100%;
  height: 45px;
  text-align: left;
  padding-left: 10px;
  border-bottom: 1px solid #efefef;
  box-sizing: border-box;
}
.addSiteType_box_l{
  float: left;
  width: 127px;
  height: 45px;
  line-height: 45px;
  font-size: 14px;
}
.addSiteType_box_r{
  float: left;
  width: 215px;
  height: 44px;
  line-height: 44px;
}
.inner{
  width: 100px;
  float: left;
  height: 44px;
  line-height: 44px;
}
.addSite_Agreement{
  padding: 10px;
  display: flex;
  text-align: left;
  align-items:center;
  font-size: 13px;
  color: #ED7523;
  .authorCheck{
    padding-right: 20px;
  }
}
.white{
  color: #ffffff;
  padding-left: 5px;
  font-size: 14px;
}
</style>
